package com.haozhen.hbase.process;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.RetryImmediatelyException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;

import javax.ws.rs.DELETE;
import java.io.IOException;
import java.time.temporal.ValueRange;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;

/**
 * @author haozhen
 * @email haozh@ync1.com
 * @date 2020/10/24  17:10
 */
public class UserFriendDeleteProcessor extends BaseRegionObserver {

    private final String table_name = "user_friends";

    private final String columnFimaly = "friends";

    /**
     * 在数据被删除时，对应的其他数据有关联的也会一并删除
     * @param e
     * @param delete
     * @param edit
     * @param durability
     * @throws IOException
     */
    @Override
    public void postDelete(ObserverContext<RegionCoprocessorEnvironment> e, Delete delete, WALEdit edit, Durability durability) throws IOException {
//        super.postDelete(e, delete, edit, durability);
       final HTableInterface user_name = e.getEnvironment().getTable(TableName.valueOf(table_name));
        NavigableMap<byte[], List<Cell>> familyCellMap = delete.getFamilyCellMap();
        List<Delete> deletes = new ArrayList<>();
        familyCellMap.forEach((key,value)->{
            if(Bytes.toString(key).equals(columnFimaly)){//friends列族
                value.forEach(cell->{
                    Delete delete1 = new Delete(cell.getQualifier());
                    delete1.addColumn(Bytes.toBytes(columnFimaly),delete.getRow());//要删除的列名 就是当前删除的 rowkey
                    deletes.add(delete1);
                });
            }
        });
        for (Delete delete1 : deletes) {
            user_name.delete(delete1);
        }

    }
}
